//
//  WmcEditNameVC.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/4/14.
//

import UIKit

// MARK: - 扩展WmcEditNameVC + WmcNavigatorProtocol

extension WmcEditNameVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.editName]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        
        var vm = WmcEditNameVM()
        
        if let viewModel = parms.context as? WmcEditNameVM {
            vm = viewModel
        }
        
        let vc = WmcEditNameVC(vm)
        return vc
    }
}

extension WmcEditNameVC: WmcVMProtocol {
    typealias VMType = WmcEditNameVM
}

// MARK: - [WmcEditNameVC]

class WmcEditNameVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "修改名字"
        
        if let name = WmcLoginManager.shared.wmcAccountModel?.name, !name.isEmpty {
            nameTextField.text = name
            clearBtn.isHidden = false
        }
    }

    // Internal

    override func makeUI() {
        view.backgroundColor = .wmc_grayH20_F7F7F7
        makeNavView(showShadow: false)

        addSubview(nameView)
        addSubview(submitBtn)

        nameView.addSubview(nameTextField)
        nameView.addSubview(clearBtn)
    }

    override func bindViewModel() {
        nameView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(57)
            make.top.equalTo(navView.snp.bottom).offset(8)
        }

        nameTextField.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.bottom.equalToSuperview()
            make.right.equalTo(clearBtn.snp.left).offset(-16)
        }

        clearBtn.snp.makeConstraints { make in
            make.width.height.equalTo(20)
            make.right.equalTo(-12)
            make.centerY.equalToSuperview()
        }

        submitBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(nameView.snp.bottom).offset(45)
            make.height.equalTo(50)
        }
    }

    // Private

    private lazy var nameView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_white_FFFFFF
        return view
    }()

    private lazy var nameTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入2~5个字纯中文姓名"
        textField.font = 17.wmc_font
        textField.textColor = .wmc_grayH2_323233
        textField.becomeFirstResponder()
        textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        return textField
    }()

    private lazy var clearBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage("close".wmc_image.yp.set(tintColor: UIColor.wmc_grayH3_505050), for: .normal)
        btn.isHidden = true
        btn.addTarget(self, action: #selector(onClearAction(_:)), for: .touchUpInside)
        return btn
    }()

    private lazy var submitBtn: UIButton = {
        let btn = UIButton(type: .custom)
        let image = UIColor.wmc_mainTheme.yp.uiImage
        btn.setBackgroundImage(image, for: .normal)
        btn.setTitle("保存", for: .normal)
        btn.setTitleColor(.wmc_white_FFFFFF, for: .normal)
        btn.titleLabel?.font = 18.wmc_font
        btn.layer.cornerRadius = 4
        btn.layer.masksToBounds = true
        btn.isEnabled = false
        btn.addTarget(self, action: #selector(onSubmitAction(_:)), for: .touchUpInside)
        return btn
    }()

    @objc private func textFieldDidChange(_ sender: UITextField) {
        guard let text = sender.text else {
            clearBtn.isHidden = true
            submitBtn.isEnabled = false
            return
        }
        
        if let language = UITextInputMode.activeInputModes.first?.primaryLanguage {
            if language == "zh-Hans" {
                if sender.markedTextRange == nil, text.count > 5 {
                    sender.text = (text as NSString).substring(to: 5)
                }
            } else if text.count > 5 {
                sender.text = (text as NSString).substring(to: 5)
            }
        }

        clearBtn.isHidden = (sender.text ?? "").isEmpty
        submitBtn.isEnabled = (sender.text ?? "").count > 1
    }
    
    @objc private func onSubmitAction(_ sender: UIButton) {
        guard let text = nameTextField.text else { return }
        
        view.endEditing(true)
        
        WmcHudManager.loading()
        viewModel.submit(name: text).subscribe { _ in
            WmcHudManager.dismiss()
            WmcHudManager.toast("保存成功")
            self.navigationController?.popViewController(animated: true)
            /// 名字修改成功需要发通知
            WmcNotificationManager.shared.post(type: .editUserNameSucceed, object: ["name": text])
        } onError: { error in
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
    
    @objc private func onClearAction(_ sender: UIButton) {
        nameTextField.text = nil
        submitBtn.isEnabled = false
        sender.isHidden = true
    }
}
